package com.tbl.modules.wms.controller.pda;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.google.common.collect.Maps;
import com.tbl.common.utils.PageTbl;
import com.tbl.common.utils.PageUtils;
import com.tbl.common.utils.StringUtils;
import com.tbl.modules.platform.constant.MenuConstant;
import com.tbl.modules.platform.controller.AbstractController;
import com.tbl.modules.platform.service.system.RoleService;
import com.tbl.modules.wms.constant.Constant;
import com.tbl.modules.wms.constant.EmumConstant;
import com.tbl.modules.wms.entity.allo.AlloInStorage;
import com.tbl.modules.wms.entity.allo.AlloOutStorage;
import com.tbl.modules.wms.entity.allo.AllocationDetail;
import com.tbl.modules.wms.entity.instorage.InstorageDetail;
import com.tbl.modules.wms.entity.interfacelog.InterfaceDo;
import com.tbl.modules.wms.entity.move.MoveInStorage;
import com.tbl.modules.wms.entity.move.MoveOutStorage;
import com.tbl.modules.wms.entity.outstorage.AllOutStorage;
import com.tbl.modules.wms.entity.outstorage.OutStorageDetail;
import com.tbl.modules.wms.entity.split.RfidBind;
import com.tbl.modules.wms.entity.split.Split;
import com.tbl.modules.wms.entity.split.SplitInstorage;
import com.tbl.modules.wms.entity.storageinfo.StorageInfo;
import com.tbl.modules.wms.service.allo.AlloInStorageService;
import com.tbl.modules.wms.service.allo.AlloOutStorageService;
import com.tbl.modules.wms.service.allo.AllocationDetailService;
import com.tbl.modules.wms.service.baseinfo.ShelfService;
import com.tbl.modules.wms.service.instorage.InstorageDetailService;
import com.tbl.modules.wms.service.interfacelog.InterfaceDoService;
import com.tbl.modules.wms.service.inventory.RfidBindService;
import com.tbl.modules.wms.service.move.MoveInStorageService;
import com.tbl.modules.wms.service.move.MoveOutStorageService;
import com.tbl.modules.wms.service.outstorage.AllOutStorageService;
import com.tbl.modules.wms.service.outstorage.OutStorageDetailService;
import com.tbl.modules.wms.service.pda.SplitInstorageService;
import com.tbl.modules.wms.service.pda.SplitService;
import com.tbl.modules.wms.service.storageinfo.StorageInfoService;
import com.tbl.modules.wms.service.webservice.client.WmsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 拆分控制层
 * @author 70486
 */
@Controller
@RequestMapping("/split")
public class SplitController extends AbstractController {

    /**
     * 出库汇总
     */
	@Autowired
	private AllOutStorageService allOutStorageService;
    /**
     * 库存
     */
    @Autowired
    private StorageInfoService storageInfoService;
    /**
     * 角色
     */
    @Autowired
    private RoleService roleService;
    /**
     * wms调用入口
     */
    @Autowired
    private WmsService wmsService;
    /**
     * 入库详情
     */
    @Autowired
    private InstorageDetailService instorageDetailService;
    /**
     * 接口执行管理
     */
    @Autowired
    private InterfaceDoService interfaceDoService;
    /**
     * 调拨入库
     */
    @Autowired
    private AlloInStorageService alloInStorageService;
    /**
     * 调拨出库
     */
    @Autowired
    private AlloOutStorageService alloOutStorageService;
    /**
     * 调拨单明细
     */
    @Autowired
    private AllocationDetailService allocationDetailService;
    /**
     * 移库入库
     */
    @Autowired
    private MoveInStorageService moveInStorageService;
    /**
     * 移库出库
     */
    @Autowired
    private MoveOutStorageService moveOutStorageService;
    /**
     * 出库明细
     */
    @Autowired
    private OutStorageDetailService outStorageDetailService;
    /**
     * rfid绑定
     */
    @Autowired
    private RfidBindService rfidBindService;
    /**
     * 拆分库存
     */
    @Autowired
    private SplitService splitService;
    /**
     * 拆分入库
     */
    @Autowired
    private SplitInstorageService splitInstorageService;
    /**
     * 库位服务
     */
    @Autowired
    private ShelfService shelfService;

    /**
     * 返回拆分页面
     * @return ModelAndView
     */
    @RequestMapping("/toList")
    public ModelAndView toList() {
        ModelAndView mv = this.getModelAndView();
        mv.addObject("operationCode", roleService.selectOperationByRoleId(getSessionUser().getRoleId(), MenuConstant.splitIng));
        mv.setViewName("techbloom/split/split_list");
        return mv;
    }
    
    /**
     * 拆分数据列表
     * @param queryJsonString 查询条件
     * @return Map<String , Object>
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Map<String, Object> list(String queryJsonString) {
        Map<String, Object> map = new HashMap<>(4);
        if (!StringUtils.isEmpty(queryJsonString)) {
            map = JSON.parseObject(queryJsonString);
        }
        //okk
        map.put("org", Arrays.asList(getSessionUser().getFactoryCode().split(",")));
        PageTbl page = this.getPage();
        PageUtils pageStorInfo = splitService.getList(page, map);
        page.setTotalRows(pageStorInfo.getTotalCount() == 0 ? 1 : pageStorInfo.getTotalCount());
        map.put("rows", pageStorInfo.getList());
        map.put("total", pageStorInfo.getTotalPage() == 0 ? 1 : pageStorInfo.getTotalPage());
        executePageMap(map, page);
        return map;
    }

    /**
     * 冻结
     * @param ids 库存主键
     * @return Map<String , Object>
     */
    @RequestMapping(value = "/frozen")
    @ResponseBody
    public Map<String, Object> frozen(String ids) {
        Map<String, Object> map = new HashMap<>(2);
        StorageInfo storageInfoEntity = new StorageInfo();
        storageInfoEntity.setState(Constant.INT_ZERO);
        boolean result = storageInfoService.update(storageInfoEntity,new EntityWrapper<StorageInfo>()
                .in("ID",Arrays.stream(ids.split(",")).map(Long::parseLong).collect(Collectors.toList())));
        map.put("msg", result ? "冻结成功！" : "冻结失败！");
        map.put("result", result);
        return map;
    }

    /**
     * 解冻
     * @param ids 库存主键
     * @return Map<String,Object>
     */
    @RequestMapping(value = "/unFrozen")
    @ResponseBody
    public Map<String, Object> unFrozen(String ids) {
        Map<String, Object> map = new HashMap<>(2);
        StorageInfo storageInfoEntity = new StorageInfo();
        storageInfoEntity.setState(Constant.INT_ONE);
        boolean result = storageInfoService.update(storageInfoEntity,new EntityWrapper<StorageInfo>()
                .in("ID",Arrays.stream(ids.split(",")).map(Long::parseLong).collect(Collectors.toList())));
        map.put("msg", result ? "解冻成功！" : "解冻失败！");
        map.put("result", result);
        return map;
    }

    /**
     * 消库
     * @param ids 库存主键
     * @return Map<String,Object>
     */
    @RequestMapping(value = "/removeStorageInfo")
    @ResponseBody
    public Map<String,Object> removeStorageInfo(String ids) {
        Map<String, Object> resultMap = Maps.newHashMap();
        storageInfoService.selectBatchIds(Arrays.stream(ids.split(",")).map(Long::parseLong).collect(Collectors.toList()))
            .forEach(storageInfo -> {
                List<InstorageDetail> lstInstorageDetail = instorageDetailService.selectByMap(new HashMap<String, Object>(1){{
                    put("RFID", storageInfo.getRfid());
                }});
                if (lstInstorageDetail.size()>0){
                    InstorageDetail instorageDetail = lstInstorageDetail.get(0);
                    instorageDetail.setState(EmumConstant.instorageDetailState.PACKAGED.getCode());
                    instorageDetailService.updateById(instorageDetail);
                }
                shelfService.setShelfState(storageInfo.getShelfCode(),storageInfo.getOrg(),storageInfo.getWarehouseCode(),1);
                storageInfoService.deleteById(storageInfo.getId());
            });
        resultMap.put("result", true);
        resultMap.put("msg", "删除成功！");
        return resultMap;
    }

    /**
     * 保存/修改质保号
     * @param storageInfo 库存信息
     * @return Map<String,Object>
     */
    @RequestMapping(value = "/save")
    @ResponseBody
    public Map<String, Object> save(StorageInfo storageInfo) {
        Map<String, Object> map = Maps.newHashMap();
        //新质保号
        String newQacode = storageInfo.getQaCode();
        //原库存
        StorageInfo oldStorageInfo = storageInfoService.selectById(storageInfo.getId());

        try {
            if(oldStorageInfo!=null && StringUtils.isNotBlank(oldStorageInfo.getBatchNo())){
                AllOutStorage allOutStorage = new AllOutStorage();
                allOutStorage.setQaCode(oldStorageInfo.getQaCode());
                allOutStorageService.update(allOutStorage, new EntityWrapper<AllOutStorage>()
                        .eq("BATCH_NO", oldStorageInfo.getBatchNo()));

                AlloInStorage alloInStorage = new AlloInStorage();
                alloInStorage.setQaCode(oldStorageInfo.getQaCode());
                alloInStorageService.update(alloInStorage, new EntityWrapper<AlloInStorage>()
                        .eq("BATCH_NO", oldStorageInfo.getBatchNo()));

                AlloOutStorage alloOutStorage = new AlloOutStorage();
                alloOutStorage.setQaCode(oldStorageInfo.getQaCode());
                alloOutStorageService.update(alloOutStorage, new EntityWrapper<AlloOutStorage>()
                        .eq("BATCH_NO", oldStorageInfo.getBatchNo()));

                AllocationDetail allocationDetail = new AllocationDetail();
                allocationDetail.setQaCode(oldStorageInfo.getQaCode());
                allocationDetailService.update(allocationDetail, new EntityWrapper<AllocationDetail>()
                        .eq("BATCH_NO", oldStorageInfo.getBatchNo()));

                InstorageDetail instorageDetail = new InstorageDetail();
                instorageDetail.setQaCode(oldStorageInfo.getQaCode());
                instorageDetailService.update(instorageDetail, new EntityWrapper<InstorageDetail>()
                        .eq("BATCH_NO", oldStorageInfo.getBatchNo()));

                MoveInStorage moveInStorage = new MoveInStorage();
                moveInStorage.setQaCode(oldStorageInfo.getQaCode());
                moveInStorageService.update(moveInStorage, new EntityWrapper<MoveInStorage>()
                        .eq("BATCH_NO", oldStorageInfo.getBatchNo()));

                MoveOutStorage moveOutStorage = new MoveOutStorage();
                moveOutStorage.setQaCode(oldStorageInfo.getQaCode());
                moveOutStorageService.update(moveOutStorage, new EntityWrapper<MoveOutStorage>()
                        .eq("BATCH_NO", oldStorageInfo.getBatchNo()));

                OutStorageDetail outStorageDetail = new OutStorageDetail();
                outStorageDetail.setQaCode(oldStorageInfo.getQaCode());
                outStorageDetailService.update(outStorageDetail, new EntityWrapper<OutStorageDetail>()
                        .eq("BATCH_NO", oldStorageInfo.getBatchNo()));

                RfidBind rfidBind = new RfidBind();
                rfidBind.setQaCode(oldStorageInfo.getQaCode());
                rfidBindService.update(rfidBind, new EntityWrapper<RfidBind>().eq("BATCH_NO", oldStorageInfo.getBatchNo()));

                Split split = new Split();
                split.setQaCode(oldStorageInfo.getQaCode());
                splitService.update(split, new EntityWrapper<Split>().eq("BATCH_NO", oldStorageInfo.getBatchNo()));

                SplitInstorage splitInstorage = new SplitInstorage();
                splitInstorage.setQaCode(oldStorageInfo.getQaCode());
                splitInstorageService.update(splitInstorage, new EntityWrapper<SplitInstorage>()
                        .eq("BATCH_NO", oldStorageInfo.getBatchNo()));

                oldStorageInfo.setQaCode(newQacode);
                storageInfoService.updateById(oldStorageInfo);

                interfaceDoService.selectList(new EntityWrapper<InterfaceDo>()
                        .like("QACODE", oldStorageInfo.getQaCode())
                        .or().like("PARAMSINFO",oldStorageInfo.getQaCode())).forEach(ifd -> {
                    ifd.setParamsinfo(ifd.getParamsinfo().replace(oldStorageInfo.getQaCode(),newQacode));
                    ifd.setQacode(ifd.getQacode().replace(oldStorageInfo.getQaCode(),newQacode));
                });
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        map.put("msg", "更新成功！");
        map.put("result", true);
        return map;
    }
    
    /**
     * 退库到生产线
     * @param id 标签初始化明细表主键
     * @param type 类型：已装包的zb；库存中的kc
     * @return Map<String , Object>
     */
    @RequestMapping(value = "/returnStorage")
    @ResponseBody
    public Map<String, Object> returnStorage(String id,String type) {
        Map<String, Object> map = new HashMap<>(2);
        InstorageDetail instorageDetail = instorageDetailService.selectById(id);

        if(Constant.RETURN_STORAGE_ZB.equals(type)) {
            //已退库
            instorageDetail.setState(Constant.INT_FIVE);
            instorageDetailService.updateById(instorageDetail);
        }else if(Constant.RETURN_STORAGE_KC.equals(type)) {
        	StorageInfo storageInfo = storageInfoService.selectOne(new EntityWrapper<StorageInfo>()
                    .eq("QACODE", instorageDetail.getQaCode()));
        	if(storageInfo!=null) {
        		try {
        			//调MES退库回生产线接口
        			Map<String,Object> xmlMap = new HashMap<>(3);
        			xmlMap.put("orgid", storageInfo.getOrg());
                    xmlMap.put("userno", getSessionUser().getUsername());
        			xmlMap.put("batches", new HashMap<String,Object>(1){{
        				put("batchno",storageInfo.getBatchNo());
        			}});
        			wmsService.FEMES002(xmlMap, storageInfo.getQaCode(), storageInfo.getBatchNo());
        		} catch (Exception e) {
        			e.printStackTrace();
        		}
        		
        		//对象赋值
        		AllOutStorage allOutStorage = new AllOutStorage();
        		allOutStorage.setOrg(storageInfo.getOrg());
        		allOutStorage.setMaterialCode(storageInfo.getMaterialCode());
        		allOutStorage.setBatchNo(storageInfo.getBatchNo());
        		allOutStorage.setQaCode(storageInfo.getQaCode());
        		allOutStorage.setSalesCode(storageInfo.getSalesCode());
        		allOutStorage.setSalesName(storageInfo.getSalesName());
        		allOutStorage.setRfid(storageInfo.getRfid());
        		allOutStorage.setMeter(storageInfo.getMeter());
        		allOutStorage.setState(storageInfo.getState());
        		allOutStorage.setWarehouseCode(storageInfo.getWarehouseCode());
        		allOutStorage.setShelfCode(storageInfo.getShelfCode());
        		//退库回生产线 类型为1
        		allOutStorage.setType(EmumConstant.OtherOutstorageType.RETURN_PRODUCTION.getCode());
        		allOutStorage.setInstoragetime(storageInfo.getInStorageTime());
        		allOutStorage.setInstorageid(storageInfo.getInStorageId());
        		allOutStorage.setEntityno(storageInfo.getEntityNo());
        		allOutStorage.setOrderno(storageInfo.getOrderno());
        		allOutStorage.setOrderline(storageInfo.getOrderline());
        		allOutStorage.setDishnumber(storageInfo.getDishnumber());
        		allOutStorageService.insert(allOutStorage);

        		//删除库存数据,把标签表状态设为已退库，已退库的可以重新入库
                storageInfoService.deleteById(storageInfo.getId());
                //状态：已退库
                instorageDetail.setState(EmumConstant.instorageDetailState.RETIRED.getCode());
                instorageDetailService.updateById(instorageDetail);
        	}
        }
        
        map.put("msg", "退库回生产线成功！");
        map.put("result", true);
        return map;
    }

    /**
     * RFID绑定
     * @return ModelAndView
     */
    @RequestMapping(value = "/bind")
    public ModelAndView bind() {
        ModelAndView mv = this.getModelAndView();
        mv.setViewName("techbloom/stock/rfid");
        return mv;
    }

    /**
     * 导出Excel
     */
    @RequestMapping(value = "/toExcel.do")
    @ResponseBody
    public void toExcel() {
        Map<String, Object> map = new HashMap<>(8);
        //得到要导出的ids
        map.put("ids", request.getParameter("ids"));
        map.put("factoryCode", request.getParameter("queryFactoryCode"));
        map.put("warehouseId", request.getParameter("queryWarehousecode"));
        map.put("shelfId", request.getParameter("queryShelfCode"));
        map.put("materialName", request.getParameter("queryMaterialName"));
        map.put("qaCode", request.getParameter("queryQaCode"));
        map.put("batchNo", request.getParameter("queryBatchNo"));
        //okk
        map.put("org", Arrays.asList(getSessionUser().getFactoryCode().split(",")));
        storageInfoService.toExcel(response,"",storageInfoService.getAllLists(map),
                request.getParameter("queryExportExcelIndex").split(","));
    }

    /**
     * 获取图表数据"库龄"占比
     * @return Map<String , Object>
     */
    @RequestMapping(value = "/getLibraryAge")
    @ResponseBody
    public Map<String, Object> getLibraryAge() {
        return storageInfoService.getLibraryAge();
    }

}
